package com.harmonk.firstscene.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.harmonk.firstscene.db.dao.TrafficEventDao
import com.harmonk.firstscene.db.dao.VehicleDao
import com.harmonk.firstscene.db.dao.PersonDao
import com.harmonk.firstscene.db.dao.EventNoteDao
import com.harmonk.firstscene.db.dao.QuickNoteDao
import com.harmonk.firstscene.db.dao.RoadDao
import com.harmonk.firstscene.db.entity.TrafficEvent
import com.harmonk.firstscene.db.entity.Vehicle
import com.harmonk.firstscene.db.entity.Person
import com.harmonk.firstscene.db.entity.EventNote
import com.harmonk.firstscene.db.entity.QuickNote
import com.harmonk.firstscene.db.entity.Road

/**
 * 应用数据库类
 * 
 * 使用 Room 持久化库管理 SQLite 数据库
 */
@Database(
    entities = [
        TrafficEvent::class,
        Vehicle::class,
        Person::class,
        EventNote::class,
        QuickNote::class,
        Road::class,
    ],
    version = 1,
    exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun trafficEventDao(): TrafficEventDao
    abstract fun vehicleDao(): VehicleDao
    abstract fun personDao(): PersonDao
    abstract fun trafficNoteDao(): EventNoteDao
    abstract fun quickNoteDao(): QuickNoteDao
    abstract fun roadDao(): RoadDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        /**
         * 获取数据库实例
         * 
         * 使用双重检查锁定实现单例模式
         * 
         * @param context 应用上下文
         * @return AppDatabase 实例
         */
        fun getDatabase(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "app_database"
                )
                    // 添加数据库迁移策略
                    .fallbackToDestructiveMigration(false) // 在没有迁移策略时重新创建数据库
                .build()
                INSTANCE = instance
                instance
            }
        }
    }
}